import random

import cv2
import numpy as np
from util import imageUtils
kColCount = 5
kMaxInputImageSize = 140
xnum = kColCount
ynum = 5

def imagemarshal(face_image,faceList,originimage,kMaxInputImageSize=kMaxInputImageSize,kColCount=kColCount,ynum=ynum):
    input_count = len(faceList)
    #print(input_count)
    row_count = (input_count +kColCount - 1)/kColCount
    print('row_count is ',row_count)
    #firstImg = cv2.imread(faceList[0])
    outImage = np.zeros((kMaxInputImageSize*ynum,kMaxInputImageSize*kColCount,3), originimage.dtype)
    inputs = []
    error = {}
    output = {'x':0,'y':0,'w':kMaxInputImageSize*kColCount,'h':kMaxInputImageSize*ynum,'src':face_image}
    for i,img in enumerate(faceList):
        #img = cv2.imread(f)
        if img is None:
            error = {'code':'loads img error','message':'cant load image file:'}
            break
        fh, fw = img.shape[0], img.shape[1]
        #print('face is ',fw,fh)
        if fh > kMaxInputImageSize or fw > kMaxInputImageSize:
            img = imageUtils.smallPic(img,kMaxInputImageSize-10)
            #print("大图",img.shape)
        elif fh <kMaxInputImageSize-20 and fw <kMaxInputImageSize-20:
            img = imageUtils.smallPic(img, kMaxInputImageSize - 10)
            #print("小图",fh, fw, img.shape)
        row = i//kColCount
        col = i % kColCount
        #print('row is ',row,col,fh,fw)
        fh, fw = img.shape[0], img.shape[1]
        #print('row is ', row, col, fh, fw)
        x = col * kMaxInputImageSize + (kMaxInputImageSize-fw)/2
        y = row * kMaxInputImageSize + (kMaxInputImageSize-fh)/2
        h = fh
        w = fw
        pic = {'x':x,'y':y,'h':h,'w':w,'src':''}
        inputs.append(pic)

        #print('inputimage is ',i,x,y,w,h)
        #print('outImage is ',int(y),int(h)+int(y),int(x),int(x)+int(w))
        outImage[int(y):int(h)+int(y),int(x):int(x)+int(w)] = img[0:int(h), 0:int(w)]
    cv2.imwrite(face_image, outImage)

    return {'output':output,'inputs':inputs,'error':error}
